package com.oauth.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class StringFormatUtil {

    public static String joinFormat(String split, String... joiners) {
        return joinFormat(split, false, false, joiners);
    }
    
    /**
     * 合并字符串
     * @param split 分隔符
     * @param isHead 字符串前是否加分隔符
     * @param isEnd 字符串后是否加分隔符
     * @param joiners 要合并的字符串
     */
    public static String joinFormat(String split, boolean isHead, boolean isEnd, String... joiners) {
        if(Objects.isNull(joiners)) {
            return split;
        }
        
        if(Objects.isNull(split)) {
            return Arrays.asList(joiners).stream().collect(Collectors.joining());
        }
        
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < joiners.length; i++) {
            if(i == 0 && isHead) {
                builder.append(String.format(split + "%s", joiners[i]));
            }else if (i == joiners.length -1 && isEnd) {
                builder.append(String.format(split + "%s" + split, joiners[i]));
            } else {
                builder.append(String.format(split + "%s", joiners[i]));
            }
        }
        return builder.toString();
    }
    
    /**
     * 字符串首字母大写
     */
	public static String toUpperCaseFirstOne(String str) {
		if (Character.isUpperCase(str.charAt(0))) {
			return str;
		}
		return (new StringBuilder()).append(Character.toUpperCase(str.charAt(0))).append(str.substring(1)).toString();
	}
	
	/**
	 * 字符串首字母小写
	 */
	public static String toLowerCaseFirstOne(String str) {
		if (Character.isLowerCase(str.charAt(0))) {
			return str;
		}
		return (new StringBuilder()).append(Character.isLowerCase(str.charAt(0))).append(str.substring(1)).toString();
	}
	
	/**
	 * form表单格式数据(k1=v1&k2=v2..)转Map<String, String>
	 */
	public static Map<String, String> mediaFormToMap(String str) {
	    Map<String, String> params = new HashMap<>();
	    if(Objects.isNull(str)) {
	        return params;
	    }
	    
	    if(str.indexOf("?") > 0) {
	        String[] split = str.split("?");
	        str = split[1];
	    }
	    
	    for (String kv : str.split("&")) {
            if(kv.indexOf("=")  >= 0) {
                String[] split = kv.split("=");
                String key = split[0];
                String value = split[1];
                
                if(Objects.nonNull(key) && Objects.nonNull(value)) {
                    params.put(key, value);
                }
            }
        }
	    
	    return params;
    }
	
	public static void main(String[] args) {
        StringFormatUtil.mediaFormToMap("k1=v1&=k2v2");
    }
}
